import React, { Component } from 'react';
// 引入编辑器以及编辑器样式
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import { Modal, Button } from 'antd';
import { showError } from '@/utils/sysFun';

export default class BraftEditorItem extends Component {
  constructor(props) {
    super(props);
    const { value } = this.props;
    this.state = {
      content: value || '',
      modalVisible: false,
      htmlContent: '',
    };
  }

  componentWillReceiveProps(nextProps) {
    // Should be a controlled component.
    if ('value' in nextProps) {
      this.setState({ content: nextProps.value });
    }
  }

  triggerChange = changedValue => {
    // Should provide an event to pass value to Form.
    const { onChange } = this.props;
    if (onChange) {
      onChange(changedValue);
    }
  };

  uploadFn = param => {
    const { uploadApi, downloadApi, idField = 'imageId' } = this.props;
    const serverURL = uploadApi.url;
    const xhr = new XMLHttpRequest();
    const fd = new FormData();

    const successFn = () => {
      const response = JSON.parse(xhr.response);
      if (response) {
        if (response.success) {
          // 上传成功后调用param.success并传入上传后的文件地址
          param.success({
            url: `${downloadApi.url}?imageId=${response.entity[idField]}`,
          });
        } else {
          showError(uploadApi, response);
          param.error({
            msg: 'unable to upload.',
          });
        }
      } else {
        param.error({
          msg: 'unable to upload.',
        });
      }
    };

    const progressFn = event => {
      // 上传进度发生变化时调用param.progress
      param.progress((event.loaded / event.total) * 100);
    };

    const errorFn = response => {
      // 上传发生错误时调用param.errors
      param.error({
        msg: 'unable to upload.',
      });
    };

    xhr.upload.addEventListener('progress', progressFn, false);
    xhr.addEventListener('load', successFn, false);
    xhr.addEventListener('error', errorFn, false);
    xhr.addEventListener('abort', errorFn, false);

    fd.append('file', param.file);
    xhr.open('POST', serverURL, true);
    xhr.send(fd);
  };

  // 控制弹窗显示隐藏
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  preview = () => {
    const { content } = this.state;
    this.setState({ htmlContent: content.toHTML() });
    this.handleModalVisible(true);
  };

  render() {
    const { modalVisible, content, htmlContent } = this.state;
    const editorProps = {
      value: content,
      onChange: this.triggerChange,
      media: { uploadFn: this.uploadFn }, // 使用自定义文件上传方法
      extendControls: [
        {
          key: 'preview-button',
          type: 'button',
          text: '预览',
          onClick: this.preview,
        },
      ],
    };

    return (
      <div style={{ border: '1px solid rgba(0,0,0,.2)' }}>
        <BraftEditor {...this.props} {...editorProps} />
        <Modal
          title="预览"
          visible={modalVisible}
          width={1200 * window.viewportScale}
          onCancel={() => this.handleModalVisible()}
          style={{ top: 20 * window.viewportScale }}
          footer={
            <Button key="back" onClick={() => this.handleModalVisible()}>
              关闭
            </Button>
          }
        >
          <p
            dangerouslySetInnerHTML={{
              __html: htmlContent,
            }}
          />
        </Modal>
      </div>
    );
  }
}
